﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace SH_VBoxVM_Service.Classes
{
    public class ConfigIO
    {


        /// <summary>
        /// Singleton Instance
        /// </summary>
        private static ConfigIO instance;


        ///Path: Solution\currentProjectDirectory\executablelocation\
        //private static string configPath = AppDomain.CurrentDomain.BaseDirectory;


        /// <summary>
        /// Path: Windows\System32 very standard... but lets see if its possible to read/write from here.
        /// If not I will use the AppDomain solution.
        /// </summary>
        private static string configPath = @"C:\Windows\System32\";

        /// <summary>
        /// Name of the Configuration File.
        /// It's in XML format.
        /// </summary>
        private static string configFileName = "SH_VBox_ConfigService.xml";

        /// <summary>
        /// File and Path concatanated of the XML file.
        /// </summary>
        private static string filexml = string.Format(@"{0}\{1}", configPath, configFileName);

        /// <summary>
        /// Location of the Virtual Machines Folder
        /// </summary>
        public static string vmsFolderPath { get; set; }

        /// <summary>
        /// Location of the VBoxManage Folder
        /// </summary>
        public static string vbmFolderPath { get; set; }




        /// <summary>
        /// List that will save all the VMs.
        /// Need to find a way to store this data in a way
        /// that it will get extracted by using the VMName?
        /// maybe using Dictionary.
        /// </summary>
        private static List<string> vmlist = new List<string>();

        public static List<string> VmList { get { return vmlist; } set { vmlist = value; } }
        




        //Its a Singleton class, no access to the constructor.
        private ConfigIO()
        { }


        /// <summary>
        /// Reads the Service Config File 
        /// Name of XML: "SH_VBox_ConfigService.xml"
        /// </summary>
        public static void readConfig()
        {
            //if the Xml File doesn't exist, create it and then Load, if not just load.
            if (!File.Exists(filexml))
            {
                ///default VMS folder path.
                string VmsDefaultPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                VmsDefaultPath += @"\.VirtualBox\";

                //if file doesnt exist I'll create a standard template for the user.
                XDocument newdoc =
                    new XDocument(

                        new XElement("Root",

                            new XComment("Default Folder by VirtualBox where 'VBoxManage.exe' is located"),
                            new XElement("VBOXMANAGEFOLDERLOCATION",@"C:\Program Files\Oracle\VirtualBox\"),

                            new XComment("Default Folder by VirtualBox where VirtualMachines are located"),
                            new XElement("VMSFOLDERLOCATION",VmsDefaultPath),
                            

                            new XComment("Names of the Virtual Machines in the VirtualBox Manager."),
                            new XComment("Note: VMNames are Case Sensitive."),
                            
                            new XElement("VMS",
                                
                                new XElement("VM1",
                                  new XElement("VMNAME","FirstTestVM")),
                                   
                                new XElement("VM2",
                                  new XElement ("VMNAME","ClearAll")),
                            
                                new XElement("VM3",
                                  new XElement ("VMNAME","AndAddYourOwnVMS"))
                                  
                                  
                                  ) //Closes "VMS" Element
                            )//Closes "Root" Element
                  
                    );

                newdoc.Save(filexml);
                newdoc = null;
            }
      
                

            //Now Reading the File and fill the date to the Variables for the App to use.
            XDocument doc = XDocument.Load(filexml);

            //extract everything to a List or Dictionary.

            //Saving the VBoxManage Folder Path
            vbmFolderPath = doc.Root.Element("VBOXMANAGEFOLDERLOCATION").FirstNode.ToString();

            //Saving the Virtual Machine Folder Path
            vmsFolderPath = doc.Root.Element("VMSFOLDERLOCATION").FirstNode.ToString();

            //Getting all the Child Elements in the VMS List: VM1,VM2,VM3...
            IEnumerable<XNode> vmsNodes = doc.Root.Element("VMS").Elements();
                
            //adding the Virtual Machine Names to the VmList
            foreach (XElement node in vmsNodes)
            {
                VmList.Add(node.Element("VMNAME").FirstNode.ToString());
            }

        }


        /// <summary>
        /// Saves all the Data from the Class to the XML File
        /// Name of XML: "SH_VBox_ConfigService.xml"
        /// </summary>
        public static void saveConfig()
        {
            //Debug Purposes
            //vbmFolderPath = @"savedVBoxManageFolderTest";
            //vmsFolderPath = @"savedVMSFolderTest";

            
            //VmList.Add("savedmachine");
            //VmList.Add("WIN2k");
            //VmList.Add("ExactLetters");
            //VmList.Add(item);
            //VmList.Add(item);
            //VmList.Add(item);

            XDocument newdoc =
                   new XDocument(

                       new XElement("Root",

                           new XComment("Default Folder where 'VBoxManage.exe' is located"),
                           new XElement("VBOXMANAGEFOLDERLOCATION", vbmFolderPath),

                           new XComment("Default Folder where VirtualMachines are located"),
                           new XElement("VMSFOLDERLOCATION", vmsFolderPath),


                           new XComment("Names of the Virtual Machines in the VirtualBox Manager."),
                           new XComment("Note: VMNames are Case Sensitive."), 
                           "") //Closes "Root" Elemen 
                   );

            //adding the VMS Tag.
            newdoc.Root.Add(new XElement("VMS",""));


            //add all VMS from the VmList to the VMS Tag.
            for(int i = 1; i <= VmList.Count; i++)
            {

                newdoc.Root.Element("VMS").Add( 
                                new XElement(string.Format(@"VM{0}",i),
                                       new XElement("VMNAME",VmList[i-1].ToString()))
                                        );
            }

            newdoc.Save(filexml);
            newdoc = null;

        }


        /// <summary>
        /// Singleton instance for ConfigIO class.
        /// No Need to touch this anymore.
        /// </summary>
        public static ConfigIO Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ConfigIO();
                }
                return instance;
            }
        }
    }
}

